package edu.inf3.j2ee.dao;

import edu.inf3.j2ee.entities.Group;
import edu.inf3.j2ee.framework.dbMySQL;



public final class GroupDao{

	public static Group getGroupById (long gid) throws Exception{

		Group group = new Group();
		dbMySQL db = new dbMySQL("localhost", "project", "root", "");
		
		db.connect();
		String query = "SELECT * FROM tbGroups WHERE group_id = " + gid;
		db.execQuery(query);
		
		if (db.nextRecord()){
			group.setId(db.getInt("group_id"));
			group.setName(db.getString("group_name"));
		
			db.clearResources();
			
			query = "SELECT * FROM tbPermissions WHERE permission_group_FK = " + gid;
			db.execQuery(query);
			
			while (db.nextRecord()){
				group.addPermission(db.getString("permission_value"), db.getString("permission_target"));
			}
		}
		
		db.clearResources();
		db.disconnect();
		
		return group;
	}
	
	public static void insertGroup (Group group) throws Exception{

		dbMySQL db = new dbMySQL("localhost", "project", "root", "");
		
		db.connect();
		
		String query = "INSERT INTO tbGroups (`group_id`,`group_name`) " +
						"VALUES (NULL, '" + group.getName() +"')";
		db.execQuery(query);
		db.disconnect();
	}

}
